package lvbu.wang.lvbuoperator.ui.paramset.ui;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.Html;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.qing.library.widget.CustomProgress;
import com.yzq.zxinglibrary.common.Constant;

import java.util.HashMap;
import java.util.Map;

import lvbu.wang.lvbuoperator.Quick;
import lvbu.wang.lvbuoperator.R;
import lvbu.wang.lvbuoperator.bean.JsonMessage;
import lvbu.wang.lvbuoperator.bean.MotorInfo;
import lvbu.wang.lvbuoperator.constants.ConstantsValue;
import lvbu.wang.lvbuoperator.constants.RouteConstant;
import lvbu.wang.lvbuoperator.core.BaseActivity;
import lvbu.wang.lvbuoperator.http.IotHttpHelp;
import lvbu.wang.lvbuoperator.manager.ThreadPool;
import lvbu.wang.lvbuoperator.services.BluetoothLEService;
import lvbu.wang.lvbuoperator.ui.error.IotErrorActivity;
import lvbu.wang.lvbuoperator.ui.paramset.presenter.IIotParamSetPresenter;
import lvbu.wang.lvbuoperator.ui.paramset.presenter.IotParamSetPresenterCompl;

/**
 * Created by DaiQing.Zha on 2017/2/22 0022.
 */
public class IotParamSetActivity extends BaseActivity implements IIotParamSetView,View.OnClickListener{

    private TextView mTvCurrentStatus;  //当前状态
    private TextView mTvMotorId;       //motorId
    private TextView mTvIsOnline;    //是否在线
    private TextView mTvImei;       //imei
    private TextView mTvICCID;    //iccid
    private TextView mTvBluetoothAddress;         //蓝牙地址
    private TextView mTvBluetoothConnectState; //蓝牙连接状态
    private TextView mTvFirmwareVersion;       //固件版本
    private  Button mBtnFirmwareVersion;     //固件升级
    private Button mBtnUnbind;               //解绑
    private Button mBtnBluetoothConnect; //蓝牙连接
    private Button mBtnBluetoothDisConnect;//断开连接
    private Button mBtnBluetoothSend;   //通过蓝牙获取电机数据
    private TextView mTvBLESignal;     //蓝牙信号强度
    private Button mBtnBLESignal;    //蓝牙信号强度
    private TextView mTvGSMSignal;  //GSM信号强度
    private Button mBtnGSMSignal; //GSM信号强度
    private TextView mTvVoltageStrength;  //电压
    private Button mBtnVoltageStrength; //电压
    private Button mBtnGyroAngle;      //调节陀螺仪角度
    private Button mBtnRestart;       //复位
    private TextView mTvTypeName;   //轮毂型号
    private TextView mTvCircumference;        //轮胎周长
    private TextView mTvPowerLevel;          //助力等级
    private TextView mTvAutoLockTimeSpan; //自动锁定时间
    private TextView mTvLockStatus;      //锁定状态
    private TextView mTvSpeedLimitValue;//超速报警值
    private TextView mTvBikeWeight;    //车重
    private TextView mTvLoadWeight;  //载重
    private TextView mTvBarcode;             //对应的二维码
    private LinearLayout mLlERM;            //二维码

    private LinearLayout mLlTypeName;                 //轮毂型号
    private LinearLayout mLlCircumference;          //轮胎周长
    private LinearLayout mLlPowerLevel;            //助力等级
    private LinearLayout mLlAutoLockTimeSpan;    //自动锁定时间
    private LinearLayout mLlLockStatus;          //锁定状态
    private LinearLayout mLlSpeedLimitValue;   //超速报警
    private LinearLayout mLlBikeWeight;           //车重
    private LinearLayout mLlLoadWeight;          //载重



    private  Button mBtnStopTurn;             //电机停转
    private  Button mBtnSimulateRide;       //模拟骑行
    private  Button mBtnDelivery;          //出库
    private  Button mBtnNormal;          //正常
    // 成员变量
    private Long mMotorId;         //motorId
    private boolean mIsOnline;  //是否在线
    private String mImei;       //imei
    private String mIccid;    //iccid
    private String mBluetoothAddress;   //蓝牙地址
    private String mTypeName;           //轮毂型号
    private String mCircumference;    //轮胎周长
    private String mStatusCode = ""; //当前状态码
    private MotorInfo mMotorInfo;         //电机
    private String mErm;                 //二维码
    private String[] mStatusCodeArr = {"01","02","03","04","05","FF"};
    private String mPowerLevel, mAutoLockTimeSpan,mLockStatus,mSpeedLimitValue,mBikeWeight,mLoadWeight; //助力等级，自动锁定，锁定状态，超速报警，车重，载重
    private ProgressDialog mProgressDialogUpgrade;  //固件升级进度条
    private IIotParamSetPresenter iIotParamSetPresenter;
    private String productId,productName;
    private RunnableT runnableT;
    Handler handlerGetIsOnline = new Handler();

    /**
     * 广播接收器
     */
    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { // 定义广播接收器，接收蓝牙消息
        @Override
        public void onReceive(Context context, final Intent intent) {
            if (intent.getAction().equals(ConstantsValue.ACTION_BLUETOOTH_CONNECT_STATE_CHANGED)) { //蓝牙状态改变
                refreshUI_bluetooth();
            }
            if (intent.getAction().equals(ConstantsValue.ACTION_BLE_SIGNAL_STRENGTH)){  //蓝牙信号强度的广播
                int rssi = intent.getIntExtra("rssi",0);
                mTvBLESignal.setText(rssi + "");
            }
        }
    };
    private Button mBtnAll;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_iot_paramset );
    }
    @Override
    protected void init() {
        mTvCurrentStatus = findView(R.id.tv_currentStatus);
        mTvMotorId = findView(R.id.tv_motorId);
        mTvIsOnline = findView(R.id.tv_isOnline);
        mTvImei = findView(R.id.tv_imei);
        mTvICCID = findView(R.id.tv_ICCID);
        mTvBluetoothAddress = findView(R.id.tv_bluetoothAddress);
        mTvBluetoothConnectState = findView(R.id.tv_bluetoothConnectState);
        mTvFirmwareVersion = findView(R.id.tv_firmwareVersion);
        mBtnFirmwareVersion = findView(R.id.btn_firmwareVersion);
        mBtnUnbind = findView(R.id.btn_unbind);
        mBtnBluetoothConnect = findView(R.id.btn_bluetoothConnect);
        mBtnBluetoothDisConnect = findView(R.id.btn_bluetoothDisConnect);
        mBtnBluetoothSend = findView(R.id.btn_bluetoothSend);
        mTvBLESignal = findView(R.id.tv_BLESignal);
        mBtnBLESignal = findView(R.id.btn_BLESignal);
        mTvGSMSignal = findView(R.id.tv_GSMSignal);
        mBtnGSMSignal = findView(R.id.btn_GSMSignal);
        mTvVoltageStrength = findView(R.id.tv_voltageStrength);
        mBtnVoltageStrength = findView(R.id.btn_voltageStrength);
        mBtnGyroAngle = findView(R.id.btn_gyroAngle);
        mBtnRestart = findView(R.id.btn_restart);
        mTvTypeName = findView(R.id.tv_typeName);
        mTvCircumference = findView(R.id.tv_circumference);
        mTvPowerLevel = findView(R.id.tv_powerLevel);
        mTvAutoLockTimeSpan = findView(R.id.tv_autolockTimespan);
        mTvLockStatus = findView(R.id.tv_lockStatus);
        mTvSpeedLimitValue = findView(R.id.tv_speedLimitValue);
        mTvBikeWeight = findView(R.id.tv_bikeWeight);
        mTvLoadWeight = findView(R.id.tv_loadWeight);
        mTvBarcode = findView(R.id.tv_barcode);


        mLlTypeName = findView(R.id.ll_typeName);                 //轮毂型号
        mLlCircumference = findView(R.id.ll_circumference);          //轮胎周长
        mLlPowerLevel = findView(R.id.ll_powerLevel);            //助力等级
        mLlAutoLockTimeSpan = findView(R.id.ll_autolockTimespan);    //自动锁定时间
        mLlLockStatus = findView(R.id.ll_lockStatus);          //锁定状态
        mLlSpeedLimitValue = findView(R.id.ll_speedLimitValue);   //超速报警
        mLlBikeWeight = findView(R.id.ll_bikeWeight);           //车重
        mLlLoadWeight = findView(R.id.ll_loadWeight);          //载重
        //并发数据
        mBtnAll = findView(R.id.btn_all);
        mBtnAll.setOnClickListener(this);
        mLlERM = findView(R.id.ll_ERM);
        mBtnStopTurn = findView(R.id.btn_motorStopTurn);
        mBtnSimulateRide = findView(R.id.btn_motorSimulateRide);
        mBtnDelivery = findView(R.id.btn_motorDelivery);
        mBtnNormal = findView(R.id.btn_normal);
        mBtnUnbind.setOnClickListener(this);
        mBtnBluetoothConnect.setOnClickListener(this);
        mBtnBluetoothDisConnect.setOnClickListener(this);
        mBtnBluetoothSend.setOnClickListener(this);
        mBtnFirmwareVersion.setOnClickListener(this);
        mBtnBLESignal.setOnClickListener(this);
        mBtnGSMSignal.setOnClickListener(this);
        mBtnVoltageStrength.setOnClickListener(this);
        mBtnGyroAngle.setOnClickListener(this);
        mBtnRestart.setOnClickListener(this);
        mLlTypeName.setOnClickListener(this);
        mLlCircumference.setOnClickListener(this);
        mLlPowerLevel.setOnClickListener(this);
        mLlAutoLockTimeSpan.setOnClickListener(this);
        mLlLockStatus.setOnClickListener(this);
        mLlSpeedLimitValue.setOnClickListener(this);
        mLlBikeWeight.setOnClickListener(this);
        mLlLoadWeight.setOnClickListener(this);
        mLlERM.setOnClickListener(this);
        mBtnStopTurn.setOnClickListener(this);
        mBtnSimulateRide.setOnClickListener(this);
        mBtnDelivery.setOnClickListener(this);
        mBtnNormal.setOnClickListener(this);
        mLlERM.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                cm.setText(mErm);   //将文本内容放到系统剪贴板里。
                showToast("复制成功，可以发给朋友们了。");
                return true;
            }
        });
        iIotParamSetPresenter = new IotParamSetPresenterCompl(this);
        Intent intent = getIntent();
        Bundle bundle = intent.getBundleExtra("bundle");
        if (bundle != null){
            mMotorId = bundle.getLong("motorId",0);
            mIsOnline = bundle.getBoolean("isOnline", false);
            mImei = bundle.getString("imei");
            mBluetoothAddress = bundle.getString("bluetoothAddress");
            mIccid = bundle.getString("iccId");
            mTypeName = bundle.getString("typeName");
            mCircumference = bundle.getString("circumference");
            mStatusCode = bundle.getString("statusCode");
        }
        productId = getBluetoothProductId(this);
        productName = getBluetoothProductName(this);
        getSupportActionBar().setTitle("参数设置 - " + productName);
        mTvMotorId.setText(mMotorId + "");
        mTvImei.setText(mImei);
        mTvBluetoothAddress.setText(mBluetoothAddress);
        mTvICCID.setText(mIccid);
        mTvTypeName.setText(mTypeName);
        mTvCircumference.setText(mCircumference);
        if (mIsOnline) {
            mTvIsOnline.setText(getString(R.string.xml_paramSet_onLine));
        } else {
            mTvIsOnline.setText(getString(R.string.xml_paramSet_offLine));
        }
        registerBroadcast();
        checkNewVersion();
        if (getMotorDefault_bluetooth_connect_state() == BluetoothLEService.Bluetooth_CONNECTED) { // 已连接，断开连接
            BluetoothLEService.disConnect();  // 断开车辆蓝牙
        }
        if (getMotorDefault_bluetooth_connect_state() == BluetoothLEService.Bluetooth_UNCONNECT) { // 未连接，开始连接
            BluetoothLEService.connect(); // 连接车辆蓝牙
        }
        iIotParamSetPresenter.getMotorStatusName(this,mStatusCode);
        iIotParamSetPresenter.getMotorInfoByMotorId(this,String.valueOf(mMotorId));
        iIotParamSetPresenter.getBarcode(this,String.valueOf(mMotorId));
        iIotParamSetPresenter.getFirmwareUpgrade(this);
        runnableT = new RunnableT();
        handlerGetIsOnline.postDelayed(runnableT, 3000);
    }

    private static final String TAG = "IotParamSetActivity";
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_unbind:
                iIotParamSetPresenter.clickUnbind(this,mMotorId);
                break;
            case R.id.btn_bluetoothConnect:
                iIotParamSetPresenter.clickConnectBluetooth(this);
                break;
            case R.id.btn_bluetoothDisConnect:
                BluetoothLEService.disConnect();
                break;
            case R.id.btn_bluetoothSend:
                iIotParamSetPresenter.clickGetDataByBluetooth();
                break;
            case R.id.btn_firmwareVersion:
                iIotParamSetPresenter.clickUpdateFirmware(this,mMotorId,mImei);
                break;
            case R.id.btn_BLESignal:
                iIotParamSetPresenter.clickBleSignalStrength(this);
                break;
            case R.id.btn_GSMSignal:
                iIotParamSetPresenter.clickGSMSignalStrength(this,mMotorId);
                break;
            case R.id.btn_voltageStrength:
                iIotParamSetPresenter.clickGetVoltage(this,mMotorId);
                break;
            case R.id.btn_gyroAngle:
                iIotParamSetPresenter.clickAdjustGyroAngle(this,mMotorId);
                break;
            case R.id.btn_restart:
                iIotParamSetPresenter.clickRestart(this);
                break;
            case R.id.ll_typeName:
                iIotParamSetPresenter.clickSelectTypeName(this,mMotorId,mImei,productId);
                break;
            case R.id.ll_circumference://设置轮胎周长
                iIotParamSetPresenter.clickSelectCircumference(this,mMotorId,mImei);
                break;
            case R.id.ll_powerLevel:
                iIotParamSetPresenter.clickAdjustPowerLevel(this,mMotorId,mImei,mMotorInfo.getPowerLevel());
                break;
            case R.id.ll_autolockTimespan:
                iIotParamSetPresenter.clickAutoLockTimeSpan(this,mMotorId,mImei,mMotorInfo.getAutolockTimespan());
                break;
            case R.id.ll_lockStatus:
                iIotParamSetPresenter.clickLockStatus(this,mMotorId,mImei,mMotorInfo.getLockStatus());
                break;
            case R.id.ll_speedLimitValue:
                iIotParamSetPresenter.clickSpeedLimitValue(this,mMotorId,mImei,mMotorInfo.getSpeedLimitValue());
                break;
            case R.id.ll_bikeWeight:
                iIotParamSetPresenter.clickBikeWeight(this,mMotorId,mImei,mMotorInfo.getBikeWeight());
                break;
            case R.id.ll_loadWeight:
                iIotParamSetPresenter.clickLoadWeight(this,mMotorId,mImei,mMotorInfo.getLoadWeight());
                break;
            case R.id.ll_ERM:
                Quick.startQRCode(this,0);
//                startActivityForResult(new Intent(getContext(), CaptureActivity.class), 0);
                break;
            //{"01","02","03","04","05","FF"};
            case R.id.btn_motorStopTurn:
                iIotParamSetPresenter.clickChangeMotorStatus(this,mMotorId,getManagerId(),mStatusCodeArr[1]);//02
                break;
            case R.id.btn_motorSimulateRide:
                iIotParamSetPresenter.clickChangeMotorStatus(this,mMotorId,getManagerId(),mStatusCodeArr[2]);//03
                break;
            case R.id.btn_motorDelivery:
                iIotParamSetPresenter.clickChangeMotorStatus(this,mMotorId,getManagerId(),mStatusCodeArr[4]);//05
                break;
            case R.id.btn_normal:
                iIotParamSetPresenter.clickChangeMotorStatus(this,mMotorId,getManagerId(),mStatusCodeArr[5]);//FF
                break;
            case R.id.btn_all:
//                ThreadPool.getInstance().addTask(new Runnable() {
//                    @Override
//                    public void run() {});
                ThreadPool.getInstance().addTask(new Runnable() {
                    @Override
                    public void run() {
                        String imei = mTvImei.getText().toString().trim();
                        Log.e(TAG, "onClick: " + imei,null );
                        Map<String, Object> queryStrings = new HashMap<String, Object>();
                        queryStrings.put("imei", imei);
                        String source = IotHttpHelp.getData(RouteConstant.GET_JSON_MOTOR_MOTOR_INFO_BY_IMEI, queryStrings, true,IotParamSetActivity.this);
                        Log.e(TAG, "onClick: " + source,null );
                    }
                });
                break;
        }
    }
    @Override
    public void refreshUI_bluetooth() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (getMotorDefault_bluetooth_connect_state() == BluetoothLEService.Bluetooth_SCAN
                        || getMotorDefault_bluetooth_connect_state() == BluetoothLEService.Bluetooth_CONNECTING) { //正在扫描或者
                    mTvBluetoothConnectState.setText("蓝牙连接中···");
                }
                if (getMotorDefault_bluetooth_connect_state() == BluetoothLEService.Bluetooth_CONNECTED) { //连接成功
                    mBtnBluetoothSend.setVisibility(View.VISIBLE);
                    mBtnBluetoothDisConnect.setVisibility(View.VISIBLE);
                    mBtnBluetoothConnect.setVisibility(View.GONE);
                    mTvBluetoothConnectState.setText("[蓝牙已连接]");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    iIotParamSetPresenter.clickGetDataByBluetooth();
                }
                if (getMotorDefault_bluetooth_connect_state() == BluetoothLEService.Bluetooth_UNCONNECT) { //未连接
                    mBtnBluetoothSend.setVisibility(View.GONE);
                    mBtnBluetoothDisConnect.setVisibility(View.GONE);
                    mBtnBluetoothConnect.setVisibility(View.VISIBLE);
                    mTvBluetoothConnectState.setText("[蓝牙未连接]");
                }
            }
        });
    }

    @Override
    public void refreshUI_motorStatus(final String statusName) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if ("正常".equals(statusName)){
                    mBtnUnbind.setVisibility(View.VISIBLE);
                }else{
                    mBtnUnbind.setVisibility(View.GONE);
                }
                mTvCurrentStatus.setText(statusName);
            }
        });
    }

    @Override
    public void refreshUI_motorInfo(MotorInfo motorInfo) {
        mMotorInfo = motorInfo;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mTvFirmwareVersion.setText(mMotorInfo.getFirmwareVersion());
                mTvPowerLevel.setText(mMotorInfo.getPowerLevel() + ""); mPowerLevel = mMotorInfo.getPowerLevel() + ""; // 助力等级
                mTvAutoLockTimeSpan.setText(mMotorInfo.getAutolockTimespan() + ""); mAutoLockTimeSpan = mMotorInfo.getAutolockTimespan() + ""; // 电机自动锁定时间(单位：)
                mTvLockStatus.setText(mMotorInfo.getLockStatus() + ""); mLockStatus = mMotorInfo.getLockStatus() + ""; // 电机锁定状态：0未锁定，1锁定
                mTvSpeedLimitValue.setText(mMotorInfo.getSpeedLimitValue() + ""); mSpeedLimitValue = mMotorInfo.getSpeedLimitValue() + ""; // 超速报警值(单位：KM/小时)
                mTvBikeWeight.setText(mMotorInfo.getBikeWeight() + ""); mBikeWeight = mMotorInfo.getBikeWeight() + ""; // 车重(单位：kg)
                mTvLoadWeight.setText(mMotorInfo.getLoadWeight() + ""); mLoadWeight = mMotorInfo.getLoadWeight() + ""; // 载重（骑行人员的重量，包括行李等）(单位：kg)
            }
        });
    }

    @Override
    public void refreshUI_barcode(final String barcode) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mErm = barcode;
                mTvBarcode.setText(barcode);
            }
        });
    }

    @Override
    public void refreshUI_firmwareBtnStatus(final boolean visible) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (visible){
                    mBtnFirmwareVersion.setVisibility(View.VISIBLE);
                }else{
                    mBtnFirmwareVersion.setVisibility(View.GONE);
                }
            }
        });
    }
    @Override
    public void refreshUI_motorInfo(final String[] values) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                String mIsOnline_String = mIsOnline ? "在线":"离线";
                mTvPowerLevel.setText(Html.fromHtml(getColorText(mPowerLevel,values[0])));
                mTvCircumference.setText(Html.fromHtml(getColorText(mCircumference,values[1])));
                mTvAutoLockTimeSpan.setText(Html.fromHtml(getColorText(mAutoLockTimeSpan,values[2])));
                mTvLockStatus.setText(Html.fromHtml(getColorText(mLockStatus,values[3])));
                mTvSpeedLimitValue.setText(Html.fromHtml(getColorText(mSpeedLimitValue,values[4])));
                mTvBikeWeight.setText(Html.fromHtml(getColorText(mBikeWeight,values[5])));
                mTvIsOnline.setText(Html.fromHtml(getColorText(mIsOnline_String + "",values[6])));
                mTvLoadWeight.setText(Html.fromHtml(getColorText(mLoadWeight,values[7])));
            }
        });
    }
    @Override
    public void refreshUI_BleSignalStrength(final String value) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mTvGSMSignal.setText(value);
            }
        });
    }
    @Override
    public void refreshUI_voltageStrength(final String value) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mTvVoltageStrength.setText(value);
            }
        });
    }
    @Override
    public void refreshUI_typeName(final String type) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mMotorInfo.setTypeName(type);
                mTvTypeName.setText(type);
            }
        });
    }
    @Override
    public void refreshUI_circumference(final String value) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mMotorInfo.setCircumference(Float.valueOf(value));
                mTvCircumference.setText(value);
                mCircumference = value;
            }
        });
    }
    @Override
    public void refreshUI_powerLevel(final String value) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mMotorInfo.setPowerLevel(Integer.valueOf(value));
                mTvPowerLevel.setText(value);
                mPowerLevel = value;
            }
        });
    }
    @Override
    public void refreshUI_autoLockTimeSpan(final String value) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mMotorInfo.setAutolockTimespan(Integer.valueOf(value));
                mTvAutoLockTimeSpan.setText(value);
                mAutoLockTimeSpan = value;
            }
        });
    }
    @Override
    public void refreshUI_lockStatus(final String value) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mTvLockStatus.setText(value);
                mLockStatus = value;
            }
        });
    }
    @Override
    public void refreshUI_speedLimitValue(final String value) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mMotorInfo.setSpeedLimitValue(Integer.valueOf(value));
                mTvSpeedLimitValue.setText(value);
                mSpeedLimitValue = value;
            }
        });
    }
    @Override
    public void refreshUI_bikeWeight(final String value) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mMotorInfo.setBikeWeight(Float.valueOf(value));
                mTvBikeWeight.setText(value);
                mBikeWeight = value;
            }
        });
    }
    @Override
    public void refreshUI_loadWeight(final String value) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mMotorInfo.setLoadWeight(Float.valueOf(value));
                mTvLoadWeight.setText(value);
                mLoadWeight = value;
            }
        });
    }

    @Override
    public void preUpgradeFirmware() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mProgressDialogUpgrade.setTitle("固件升级"); // 设置ProgressDialog 标题
                mProgressDialogUpgrade.setMessage("开始升级，可能需要3-5分钟..."); // 设置ProgressDialog 提示信息
                mProgressDialogUpgrade.show();
            }
        });
    }

    @Override
    public void cancelFirmwareUpgrade() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mProgressDialogUpgrade.cancel();
            }
        });
    }
    @Override
    public void downloadingUpgradePatchF1(final int sectionAlready, final int maxSection) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mProgressDialogUpgrade.setMessage(getString(R.string.toast_paramSet_downloadingFirmware));
                mProgressDialogUpgrade.setProgress(sectionAlready);
                mProgressDialogUpgrade.setMax(maxSection);
            }
        });
    }
    @Override
    public void downloadSuccessUpgradePatchF2(final String firmwareVersion) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mMotorInfo.setFirmwareVersion(firmwareVersion);
                mProgressDialogUpgrade.setMessage(getString(R.string.toast_paramSet_downloadFinishStartInstall));
            }
        });
    }
    @Override
    public void downloadFailUpgradePatchF3() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mProgressDialogUpgrade.cancel();
                mBtnFirmwareVersion.setVisibility(View.VISIBLE);
            }
        });
    }
    @Override
    public void upgradeFirmwareSuccessF4(final String firmwareVersion) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {

                mMotorInfo.setFirmwareVersion(firmwareVersion);
                mProgressDialogUpgrade.setProgress(0);
                mProgressDialogUpgrade.cancel();
            }
        });
    }
    @Override
    public void upgradeFirmwareFailF5() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mProgressDialogUpgrade.cancel();
                mBtnFirmwareVersion.setVisibility(View.VISIBLE);
            }
        });
    }
    /*-----------------------重写方法区-----------------------*/
    @Override
    public void showProcess(final int type) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                CustomProgress.show(IotParamSetActivity.this, getProgressTipString(type),false,null);
            }
        });
    }
    @Override
    public void hideProcess() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                CustomProgress.dissMiss();
            }
        });
    }
    @Override
    public void showToast(int type) {
        showToastMsg(getToastString(type));
    }
    @Override
    public void showToast(String toast) {
        showToastMsg(toast);
    }

    @Override
    public void showToast(int type, String toast) {
        showToastMsg(getToastString(type) + toast);
    }

    /**
     * 获取自定义progress的提示信息
     * @param type
     * @return
     */
    private String getProgressTipString(int type){
        String string = "";
        if (type == PROGRESS_TYPE_NAME) string = getString(R.string.xml_paramSet_alterTypeName);   //正在更改轮毂型号
        if (type == PROGRESS_CIRCUMFERENCE) string = getString(R.string.xml_paramSet_alterCircumference);   //正在更改轮胎周长
        if (type == PROGRESS_ADJUST_POWER_LEVEL_ING) string = getString(R.string.xml_paramSet_adjustPowerLevelIng);   //正在调节助力等级
        if (type == PROGRESS_ADJUST_AUTO_LOCK_TIME_SPAN) string = getString(R.string.xml_paramSet_adjustAutoLockTimeSpan);   //修改自动锁定时间
        if (type == PROGRESS_ADJUST_LOCK_STATUS) string = getString(R.string.xml_paramSet_adjustLockStatus);   //修改锁定状态
        if (type == PROGRESS_ADJUST_SPEED_LIMIT_VALUE) string = getString(R.string.xml_paramSet_adjustSpeedLimitValue);   //超速报警
        if (type == PROGRESS_ADJUST_BIKE_WEIGHT) string = getString(R.string.xml_paramSet_adjustBikeWeight);   //修改车重
        if (type == PROGRESS_ADJUST_LOAD_WEIGHT) string = getString(R.string.xml_paramSet_adjustLoadWeight);   //修改载重
        if (type == PROGRESS_CHANGE_STATUS_CHANGE_ING) string = getString(R.string.xml_paramSet_changeStatusF_changeIng);   //正在修改电机状态
        if (type == PROGRESS_UNBIND) string = getString(R.string.xml_paramSet_unbindIng);   //正在解绑
        return string;
    }
    /**
     * 获取toast信息
     * @param type
     * @return
     */
    private String getToastString(int type){
        String string = "";
        if (type == TOAST_COMM_GET_DATA_ERROR) string = getString(R.string.toast_comm_getDataError);                             //获取数据失败
        if (type == TOAST_COMM_MOTOR_COMMAND_ANSWER_ERROR) string = getString(R.string.toast_comm_motorCommandAnswerError); //应答失败
        if (type == TOAST_COMM_BLE_NOT_SUPPORT) string = getString(R.string.toast_comm_bleNotSupport);           //手机不支持低功耗蓝牙
        if (type == TOAST_COMM_BLUETOOTH_NOT_OPEN) string = getString(R.string.toast_comm_bluetoothNotOpen);  //手机蓝牙尚未打开
        if (type == TOAST_COMM_BLE_CONNECTING) string = getString(R.string.toast_comm_bleConnecting);         //蓝牙连接中
        if (type == TOAST_PARAM_SET_GET_GSM_FAIL_) string = getString(R.string.toast_paramSet_getGsmFail_);         //获取GSM信号强度失败
        if (type == TOAST_PARAM_SET_GET_GSM_FAIL) string = getString(R.string.toast_paramSet_getGsmFail);         //获取GSM信号强度失败
        if (type == TOAST_COMM_BLE_IS_NOT_CONNECT) string = getString(R.string.toast_comm_bleIsNotConnect);         //蓝牙尚未连接
        if (type == TOAST_PARAM_SET_GET_VOLTAGE_FAIL) string = getString(R.string.toast_paramSet_getVoltageFail);    //获取电压失败
        if (type == TOAST_PARAM_SET_RESET_SUCCESS) string = getString(R.string.toast_paramSet_resetSuccess);    //重启操作成功
        if (type == TOAST_PARAM_SET_RESET_FAIL) string = getString(R.string.toast_paramSet_resetFail);    //重启操作失败
        if (type == TOAST_PARAM_SET_FIRMWARE_UPGRADE_FAIL) string = getString(R.string.toast_paramSet_firmwareUpgradeFail);    //固件升级失败
        if (type == TOAST_PARAM_SET_DOWNLOAD_PATCH_FAIL) string = getString(R.string.toast_paramSet_downloadUpPatchFail);  //下载固件升级包失败
        if (type == TOAST_PARAM_SET_UPGRADE_SUCCESS) string = getString(R.string.toast_paramSet_upgradeSuccess);  //升级成功
        if (type == TOAST_PARAM_SET_INSTALL_FAIL) string = getString(R.string.toast_paramSet_firmwareInstallFail);  //安装固件失败
        return string;
    }
    /**
     * 版本检测
     */
    private void checkNewVersion() {
        if (mBtnFirmwareVersion == null) {
            mBtnFirmwareVersion = (Button) this.findViewById(R.id.btn_firmwareVersion);
        }
        if (mProgressDialogUpgrade == null) {
            mProgressDialogUpgrade = new ProgressDialog(getContext());
            mProgressDialogUpgrade.setCancelable(false);
            mProgressDialogUpgrade.setCanceledOnTouchOutside(false);
            mProgressDialogUpgrade.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); // 设置进度条风格，风格为长形，有刻度的
        }
        iIotParamSetPresenter.checkNewFirmwareVersion(this,mMotorId);
    }
    /**
     * 获取带颜色的文字
     * @param param1
     * @param param2
     * @return
     */
    private String getColorText(String param1,String param2){

        return param1 + "<font color=\"#0000FF\"> (" + param2 + ") </font>";
    }
    /**
     * 注册广播接收器
     */
    private void registerBroadcast(){
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConstantsValue.ACTION_BLUETOOTH_CONNECT_STATE_CHANGED);
        filter.addAction(ConstantsValue.ACTION_BLE_SIGNAL_STRENGTH);
        filter.addAction(ConstantsValue.ACTION_BLUETOOTH_VALUE);
        registerReceiver(broadcastReceiver, filter);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0) {
            if (resultCode == RESULT_OK) {
                Bundle bundle = data.getExtras();
                final String scanResult = bundle.getString(Constant.CODED_CONTENT);
                ThreadPool.getInstance().addTask(new Runnable() {
                    @Override
                    public void run() {
                        Map<String, Object> queryStrings = new HashMap<String, Object>();
                        queryStrings.put("motorId", mMotorId);
                        queryStrings.put("managerId", getManagerId());
                        queryStrings.put("barcode", scanResult);
                        final String source = IotHttpHelp.getData(RouteConstant.Set_motorBarcode_update, queryStrings, true, getContext());
                        Log.e("mainBARCODE","source = " + source);
                        if (source.equals(JsonMessage.SuccessString)) {
                            runOnUiThread(new Runnable() {
                                public void run() {
                                    mTvBarcode.setText(scanResult);
                                }
                            });
                        } else {
                            showToastMsg(IotHttpHelp.source2Message(getContext(), source));
                        }
                    }
                });
            } else {
                showToastMsg("扫描二维码出错");
            }
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(broadcastReceiver);
        BluetoothLEService.disConnect();
        if (runnableT != null) handlerGetIsOnline.removeCallbacks(runnableT);
    }
    class RunnableT implements Runnable{
        @Override
        public void run() {
            handlerGetIsOnline.postDelayed(this, 3000);
            ThreadPool.getInstance().addTask(new Runnable() {
                @Override
                public void run() {
                    Map<String, Object> queryStrings = new HashMap<String, Object>();
                    queryStrings.put("imei", mImei);
                    String source = IotHttpHelp.getData(RouteConstant.GET_JSON_MOTOR_MOTOR_INFO_BY_IMEI, queryStrings, true, IotParamSetActivity.this);
                    if (IotHttpHelp.checkSource(source) == true) {
                        MotorInfo motorInfo = new Gson().fromJson(source, MotorInfo.class);
                        if (motorInfo.getMotorId() > 0) {
                            mIsOnline = motorInfo.getIsOnline();
                            final String isOnline_String = mIsOnline ? "在线":"离线";
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    mTvIsOnline.setText(isOnline_String);
                                }
                            });
                        }
                    }
                }
            });
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_paramset, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_seeError){
            Intent intent = new Intent(IotParamSetActivity.this, IotErrorActivity.class);
            Bundle bundle = new Bundle();
            bundle.putLong("motorId",mMotorId);
            intent.putExtra("bundle",bundle);
            startActivity(new Intent(intent));
        }
        return super.onOptionsItemSelected(item);
    }
}
